package com.css.fxfzaqbz.modules.base.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzaqbz.base.dict.repository.DictItemRepository;
import com.css.fxfzaqbz.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import com.css.fxfzaqbz.constants.FxfzConstants;
import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.modules.base.entity.NetworkanalystPath;
import com.css.fxfzaqbz.modules.base.entity.NetworkanalystVersion;
import com.css.fxfzaqbz.modules.base.service.HypergraphService;
import com.css.fxfzaqbz.modules.data.entity.Site;
import com.css.fxfzaqbz.modules.supergraph.entity.JcEmergcyShelterVo;
import com.css.fxfzaqbz.modules.supergraph.entity.TemplateEntity;
import com.css.fxfzaqbz.util.*;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.entity.SUser;
import com.css.fxfzaqbz.zcpt.sys.service.SUserService;
import com.css.fxfzaqbz.zcpt.sys.service.SysRoleService;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class HypergraphServiceImpl implements HypergraphService {
    @Value("${iServer.PathPre}")
    String iServerHttp;
    @Value("${iServer.PathPre10i}")
    String iServerHttp10i;
    @Value("${iServer.userName}")
    String userName;
    @Value("${iServer.password}")
    String password;

    //    @Resource
//    RestTemplate restTemplate;
    RestTemplate restTemplate = getRestTemplate();
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    DictItemRepository dictItemRepository;
    @Resource
    SUserService sUserService;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    private AttachmentInfoService attachmentInfoService;

    /**
     * 调度器使用的RestTemplate，超时1800s
     *
     * @return
     */
    @Override
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(1800))
                .setReadTimeout(Duration.ofSeconds(1800))
                .build();
        //解决中文乱码
        List<HttpMessageConverter<?>> msgConv = restTemplate.getMessageConverters();
        if (msgConv != null && !msgConv.isEmpty()) {
            for (int i = 0; i < msgConv.size(); i++) {
                if (msgConv.get(i).getClass().equals(StringHttpMessageConverter.class)) {
                    msgConv.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
                }
            }
        }
        return restTemplate;
    }

    /**
     * @param map type://类型
     *            WorkspaceReload//刷新指定超图工作空间数据源数据集
     *            token//获取超图服务token
     *            newNetworkanalystPath//根据起点、终点经纬度进行最佳路径分析
     *            newWorkspaceNetwork//工作空间发布交通网络分析服务
     *            importWorkspaceNetwork//工作空间导入路网数据
     * @return
     */
    @Override
    public RestResponse getServerToken(Map<String, Object> map) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/security/tokens.rjson";
            String queryType = (String) map.get("type");
            if(queryType.equals("newNetworkanalystPath") || queryType.equals("newWorkspaceNetwork") || queryType.equals("deleteWorkspace")){//10i试用版网络分析服务
                dataUrl = iServerHttp10i + "/iserver/services/security/tokens.rjson";
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userName);
            jsonObject.put("password", password);
            jsonObject.put("clientType", "NONE");//查询数量
            jsonObject.put("expiration", 60);//申请令牌的有效期，从发布令牌的时间开始计算，单位为分钟
            //System.out.println(jsonObject);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
            String token = exchange.getBody();
            String type = (String) map.get("type");
            String layerName = (String) map.get("layerName");
            if (type.equals("WorkspaceReload")) {
                String datasource = (String) map.get("datasource");//数据源
                String dataset = (String) map.get("dataset");//数据集
                //获取工作空间文件路径
                String smwuUrl = getWorkspacePathByName("map-fxfzaqbz", token);
                if (PlatformObjectUtils.isEmpty(smwuUrl)) {
                    //查询字典--超图数据源工作空间文件路径
                    DictItemEntity dte = dictItemRepository.findOneByDictItemCodeAndDictId(datasource, "100001");
                    smwuUrl = dte.getDictItemName();//工作空间文件路径
                }
                //刷新指定超图工作空间数据源数据集
                restResponse = mapLayerWorkspaceReload(smwuUrl, datasource, dataset, token);
            } else if (type.equals("token")) {//获取超图服务token
                restResponse = RestResponse.succeed(token);
            } else if (type.equals("newNetworkanalystPath")) {//根据起点、终点经纬度进行最佳路径分析
                String networkId = (String) map.get("networkId");//工作空间发布交通网络分析服务ID
                String networkUrl = (String) map.get("networkUrl");
                if (PlatformObjectUtils.isEmpty(networkUrl)) {
                    //获取交通网络分析服务路径
                    networkUrl = getNetworkUrlById(networkId);
                }
                if (PlatformObjectUtils.isNotEmpty(networkUrl)) {
                    String ssId = (String) map.get("ssId");//重点目标ID
                    double ctfw = (Double) map.get("ctfw");//出图范围km
                    String ssJzwmc = (String) map.get("ssJzwmc");//重点目标名称
                    String bncsmc = (String) map.get("bncsmc");//避难场所名称
                    double startLon = (Double) map.get("startLon");
                    double startLat = (Double) map.get("startLat");
                    double endLon = (Double) map.get("endLon");
                    double endLat = (Double) map.get("endLat");
                    //获取交通网络分析服务的最佳路径分析
                    restResponse = networkanalystPathGet(networkId, networkUrl, ssId, ctfw, ssJzwmc, bncsmc, startLon, startLat, endLon, endLat, token);
                } else {
                    restResponse = RestResponse.fail("无交通网络分析服务");
                }
            } else if (type.equals("newWorkspaceNetwork")) {//工作空间发布交通网络分析服务
                //工作空间发布交通网络分析服务
                restResponse = supermapPostWorkspace(map, token);
            } else if (type.equals("importWorkspaceNetwork")) {//工作空间导入路网数据
                /*String udbxUrl = (String) map.get("udbxUrl");//工作空间路径
                String networkDataset = (String) map.get("networkDataset");//工作空间内的网络数据集名称
                String timeStamp = System.currentTimeMillis() + "";//时间戳，用于数据集名称后缀，防止重名
                String targetDataset = "file_Network_"+timeStamp;//复制到数据库的目标数据集名称
                //工作空间导入路网数据
                restResponse = tifMapLayerToolJobPost(udbxUrl,networkDataset,targetDataset,token);
                if(restResponse.getCode() == 200){//导入成功
                    //更新路网数据表数据并刷新超图服务
                    updateNetworkDatasetData(targetDataset);
                }*/
            } else if (type.equals("workspaceRestMap")) {//工作空间发布地图服务
                //工作空间发布地图服务
                restResponse = supermapPostWorkspaceMap(map, token);
            } else if (type.equals("getRestMapUrlList")) {//获取超图工作空间全部地图服务url列表
                //获取超图工作空间全部地图服务url列表
                restResponse = supermapGetMapUrlList(map, token);
            } else if (type.equals("deleteWorkspace")) {//删除超图工作空间服务
                NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
                //根据ID逻辑删除版本
                deleteNetworkanalystVersionById(networkanalystVersion.getId());
                //删除超图工作空间服务
                restResponse = supermapDeleteWorkspace(map, token);
            } else if (type.equals("getWebprintingLayoutsList")) {//获取Web打印出图模板列表
                //获取Web打印出图模板列表
                restResponse = supermapGetTemplateEntityList(map, token);
            } else if (type.equals("uploadTemplateFile")) {//上传模板文件到超图模板目录
                //上传模板文件到超图模板目录
                restResponse = supermapPostTemplateFile(map, token);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //工作空间发布交通网络分析服务
    private RestResponse supermapPostWorkspace(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            String datasource = networkanalystVersion.getDatasource();//数据源名称
            String dataset = networkanalystVersion.getDataset();//工作空间内的网络数据集名称
            if (PlatformObjectUtils.isEmpty(smwuUrl) || PlatformObjectUtils.isEmpty(udbxUrl) || PlatformObjectUtils.isEmpty(datasource) || PlatformObjectUtils.isEmpty(dataset)) {
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //发布工作空间
//            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            String dataUrl = iServerHttp10i + "/iserver/manager/workspaces.rjson?token=" + serverToken;//10i试用版网络分析服务
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息
            JSONArray servicesTypes = new JSONArray();
            servicesTypes.add("RESTTRANSPORTATIONANALYST");//交通网络分析服务
            parameter.put("servicesTypes", servicesTypes);//发布的服务类型
            parameter.put("isMultiInstance", false);//是否启用多实例
            parameter.put("instanceCount", "");
            JSONObject transportationAnalystSetting = new JSONObject();
            JSONArray weightFieldInfos = new JSONArray();
            JSONObject weightFieldInfo = new JSONObject();
            weightFieldInfo.put("backWeightField", "SmLength");
            weightFieldInfo.put("forwardWeightField", "SmLength");
            weightFieldInfo.put("name", "SmLength");
            weightFieldInfos.add(weightFieldInfo);//权值字段信息集合，必设参数。
            transportationAnalystSetting.put("weightFieldInfos", weightFieldInfos);
            transportationAnalystSetting.put("workspaceConnectString", smwuUrl);
            transportationAnalystSetting.put("datasourceName", datasource);
            transportationAnalystSetting.put("datasetName", dataset);
            transportationAnalystSetting.put("nodeIDField", "SmNodeID");
            transportationAnalystSetting.put("edgeIDField", "SmEdgeID");
            transportationAnalystSetting.put("fromNodeIDField", "SmFNode");
            transportationAnalystSetting.put("toNodeIDField", "SmTNode");
            transportationAnalystSetting.put("initFacilityAnalyst", false);
            transportationAnalystSetting.put("directionField", "");
            parameter.put("transportationAnalystSetting", transportationAnalystSetting);//发布交通网络分析服务的环境配置类。

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
            JSONObject body = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body")).getJSONObject(0);
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            String serviceAddress = body.getString("serviceAddress");
            String serviceType = body.getString("serviceType");
            if (PlatformObjectUtils.isNotEmpty(serviceAddress) && PlatformObjectUtils.isNotEmpty(serviceType) && serviceType.equals("RESTTRANSPORTATIONANALYST")) {
                networkanalystVersion.setId(UUIDGenerator.getUUID());
                String networkUrl = serviceAddress + "/networkanalyst/" + dataset + "@" + datasource;
                networkanalystVersion.setNetworkUrl(networkUrl);
                //获取新的交通网络分析服务版本号
                String version = getNetworkanalystVersionCode();
                networkanalystVersion.setVersion(version);
                networkanalystVersion.setDelFlag(YNEnum.N.toString());
                networkanalystVersion.setCreateUser(PlatformSessionUtils.getUserId());
                String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
                SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
                String userName = sUser.getUserName();
                networkanalystVersion.setCreateUserName(userName);
                networkanalystVersion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                //获取用户的所属省份ID
                String createProvinceId = getUserProvinceId();
                networkanalystVersion.setCreateProvinceId(createProvinceId);
                //保存交通网络分析服务版本信息
                saveNetworkanalystVersion(networkanalystVersion);
                restResponse = RestResponse.succeed("发布成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //超图工作空间发布地图服务
    private RestResponse supermapPostWorkspaceMap(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            if (PlatformObjectUtils.isEmpty(smwuUrl)) {
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //发布工作空间
            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息
            JSONArray servicesTypes = new JSONArray();
            servicesTypes.add("RESTMAP");//地图服务
            parameter.put("servicesTypes", servicesTypes);//发布的服务类型
            parameter.put("isMultiInstance", false);//是否启用多实例
            parameter.put("instanceCount", "");
            parameter.put("mapEditable", true);
            parameter.put("mapDpi", 96);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
            JSONObject body = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body")).getJSONObject(0);
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            String serviceAddress = body.getString("serviceAddress");
            String serviceType = body.getString("serviceType");
            if (PlatformObjectUtils.isNotEmpty(serviceAddress) && PlatformObjectUtils.isNotEmpty(serviceType) && serviceType.equals("RESTMAP")) {
                networkanalystVersion.setId(UUIDGenerator.getUUID());
                String networkUrl = serviceAddress;
                networkanalystVersion.setNetworkUrl(networkUrl);
                //获取新的地图服务版本号
                String version = getNewWorkspaceVersionCode();
                networkanalystVersion.setVersion(version);
                networkanalystVersion.setDelFlag(YNEnum.N.toString());
                networkanalystVersion.setCreateUser(PlatformSessionUtils.getUserId());
                String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
                SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
                String userName = sUser.getUserName();
                networkanalystVersion.setCreateUserName(userName);
                networkanalystVersion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                //获取用户的所属省份ID
                String createProvinceId = getUserProvinceId();
                networkanalystVersion.setCreateProvinceId(createProvinceId);
                //保存基础地理数据超图地图服务版本信息
                saveNetworkanalystVersion(networkanalystVersion);
                restResponse = RestResponse.succeed(version);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //获取超图工作空间全部地图服务url列表
    private RestResponse supermapGetMapUrlList(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            //地图服务url--http://10.13.155.192:8090/iserver/services/map-testfileWorkspace/rest
            String url = (String) map.get("mapUrl");
            if (PlatformObjectUtils.isEmpty(url)) {
                RestResponse.fail("无地图服务");
            }
            //获取地图服务全部地图url
            String dataUrl = url + "/maps.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONArray body = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return null;
            }
            if (body.size() > 0) {
                List<String> mapPaths = new ArrayList<>();
                for (int i = 0; i < body.size(); i++) {
                    String path = body.getJSONObject(i).getString("path");
                    mapPaths.add(path);
                }
                restResponse = RestResponse.succeed(mapPaths);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //删除超图工作空间服务
    private RestResponse supermapDeleteWorkspace(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            if (PlatformObjectUtils.isEmpty(smwuUrl)) {
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //删除工作空间服务
//            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            String dataUrl = iServerHttp10i + "/iserver/manager/workspaces.rjson?token=" + serverToken;//10i试用版网络分析服务
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.PUT, entity, String.class);
            JSONObject body = JSON.parseObject(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            boolean bool = body.getBoolean("succeed");
            if (bool) {
                restResponse = RestResponse.succeed("删除超图工作空间服务成功！");
            } else {
                restResponse = RestResponse.succeed("删除超图工作空间服务失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    /*//超图服务工具--工作空间导入路网数据
    private RestResponse tifMapLayerToolJobPost(String udbxUrl, String networkDataset, String targetDataset, String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/sps.WorkflowProcessFactory.models.tif发布:工作空间导入路网数据/jobs?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject jsonObject = new JSONObject();
            JSONObject parameter = new JSONObject();
            //--server=E:/MapData/testfilenetwork/filenetwork.udbx --dbType=udbx --providerType=sdx
            String dataConnInfo = "--server="+udbxUrl+" --dbType=udbx --providerType=sdx";
            parameter.put("String", dataConnInfo);//工作空间数据源连接信息
            parameter.put("String_1", networkDataset);//网络数据集名称
            parameter.put("String_2", targetDataset);//目标数据集名称
            jsonObject.put("parameter", parameter);
            JSONArray environment = new JSONArray();
            jsonObject.put("environment", environment);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            // result.put("result", body.getString("jobID"));

            restResponse = tifMapLayerToolJobGet(body.getString("jobID"), serverToken);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    private RestResponse tifMapLayerToolJobGet(String jobID, String serverToken) {
        JSONObject result = new JSONObject();
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/jobs/" + jobID + ".json?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            if (!body.getJSONObject("state").getBooleanValue("success")
                    && !body.getJSONObject("state").getString("runState").equals("RUNNING")) {
                return RestResponse.fail("未获取到数据！");
            }
            BigDecimal percent = body.getJSONObject("progress").getBigDecimal("percent");
            while (percent.compareTo(BigDecimal.valueOf(100)) < 0) {
                Thread.sleep(1000);
                //获取任务执行百分比
                percent = tifMapLayerToolJobGetPercent(jobID, serverToken);
                if (percent.compareTo(BigDecimal.valueOf(-1)) == 0) {
                    return RestResponse.fail("该任务未获取到数据！");
                }
            }
            result.put("result", "获取成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return tifMapLayerToolJobGet(jobID, serverToken);
        }
        return RestResponse.succeed(result);
    }

    //获取任务执行百分比
    private BigDecimal tifMapLayerToolJobGetPercent(String jobID, String serverToken) {
        BigDecimal jobPercent = BigDecimal.ZERO;
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/jobs/" + jobID + ".json?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return jobPercent;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return jobPercent;
            }
            if (!body.getJSONObject("state").getBooleanValue("success")
                    && !body.getJSONObject("state").getString("runState").equals("RUNNING")) {
                return jobPercent;
            }
            BigDecimal percent = body.getJSONObject("progress").getBigDecimal("percent");
            jobPercent = percent;
        } catch (Exception e) {
            e.printStackTrace();
            return jobPercent;
        }
        return jobPercent;
    }*/

    //获取工作空间文件路径
    private String getWorkspacePathByName(String smwuName, String serverToken) {
        String smwuPath = "";
        try {
            String dataUrl = iServerHttp + "/iserver/manager/providers.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONArray body = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return null;
            }
            for (int i = 0; i < body.size(); i++) {
                JSONObject obj = (JSONObject) body.get(i);
                if (obj.getString("name").equals(smwuName)) {
                    smwuPath = obj.getJSONObject("config").getString("workspacePath");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return smwuPath;
    }

    //刷新指定超图工作空间数据源数据集
    private RestResponse mapLayerWorkspaceReload(String smwuUrl, String datasource, String dataset, String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/manager/workspaces/workspacereload.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //刷新指定数据源数据集时的参数设置，形式为{"workspaceConnectionInfo":"C:/Users/lenovo/Desktop/192/MapData/fxfzdzzh/fxfzdzzh10/fxfzdzzh.smwu","isForce":true,"datasets":{"fxfzdzzh":["dzzh_slide_result_intensity"]}}
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("workspaceConnectionInfo", smwuUrl);
            jsonObject.put("isForce", true);
            JSONObject datasets = new JSONObject();
            JSONArray datasetArray = new JSONArray();
            datasetArray.add(dataset);
            datasets.put(datasource, datasetArray);//数据源数据集名称
            jsonObject.put("datasets", datasets);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
            JSONObject body = JSON.parseObject(exchange.getBody());
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            if (body.getBooleanValue("succeed")) {
                restResponse = RestResponse.succeed("刷新成功");
            } else {
                restResponse = RestResponse.fail("刷新失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //刷新指定超图工作空间数据源数据集
    @Override
    public boolean getWorkspaceReload(String dataset) {
        boolean bool = false;
        Map<String, Object> map = new HashMap<>();
        map.put("type", "WorkspaceReload");
        map.put("datasource", "fxfzaqbz");//数据源（数据库名）
        map.put("dataset", dataset);//数据集（表名）
        RestResponse restResponse1 = getServerToken(map);//刷新指定超图工作空间数据源数据集
        if (restResponse1.getCode() == 200) {
            //刷新成功
            bool = true;
        }

        return bool;
    }

    //获取超图服务token
    @Override
    public String getToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "token");
        RestResponse restResponse = getServerToken(map);
        String token = (String) restResponse.getData();

        return token;
    }

    //获取交通网络分析服务的最佳路径分析
    private RestResponse networkanalystPathGet(String networkId, String networkUrl, String ssId, Double ctfw, String ssJzwmc, String bncsmc,
                                               Double startLon, Double startLat, Double endLon, Double endLat, String serverToken) {
        RestResponse restResponse = null;//最佳路径空间数据
        try {
//            String dataUrl = iServerHttp + "/iserver/services/transportationAnalyst-roadnetwork/rest/networkanalyst/roadnetwork_Network@roadnetwork/path.rjson?token=" + serverToken;
//            String dataUrl = iServerHttp + "/iserver/services/transportationAnalyst-testnetwork/rest/networkanalyst/testnetwork_Network_all@testnetwork/path.rjson?token=" + serverToken;
            String dataUrl = networkUrl + "/path.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

            JSONArray nodes = new JSONArray();
            JSONObject startLonLat = new JSONObject();
            startLonLat.put("x", startLon);
            startLonLat.put("y", startLat);
            nodes.add(startLonLat);
            JSONObject endLonLat = new JSONObject();
            endLonLat.put("x", endLon);
            endLonLat.put("y", endLat);
            nodes.add(endLonLat);
            JSONObject parameter = new JSONObject();
            JSONObject resultSetting = new JSONObject();
            resultSetting.put("returnRoutes", true);
            resultSetting.put("returnPathGuides", false);
            parameter.put("resultSetting", resultSetting);
            String nodes1 = JSON.toJSONString(nodes);
            String parameter1 = JSON.toJSONString(parameter);
            dataUrl = dataUrl + "&nodes={nodes1}&parameter={parameter1}";

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class, nodes1, parameter1);
            JSONObject body = JSON.parseObject(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return null;
            }
            JSONArray paths = body.getJSONArray("pathList");
            if (paths != null && paths.size() > 0) {
                double routeLength = 0;
                String line = "MULTILINESTRING((";
                for (int i = 0; i < paths.size(); i++) {
                    JSONObject path = paths.getJSONObject(i);
                    if (path != null && path.toString().contains("route")) {
                        double length = path.getJSONObject("route").getDouble("length");
                        routeLength += length;
                        JSONArray points = path.getJSONObject("route").getJSONObject("line").getJSONArray("points");
                        if (points != null && points.size() > 0) {
                            if (!line.equals("MULTILINESTRING((")) {
                                line += "),(";
                            }
                            for (int j = 0; j < points.size(); j++) {
                                JSONObject point = (JSONObject) points.get(j);
                                String x = point.getString("x");
                                String y = point.getString("y");
                                if (j > 0) {
                                    line += ",";
                                }
                                line += x + " " + y;
                            }
                        }
                    }
                }
                line += "))";
                if (line.equals("MULTILINESTRING(())")) {
                    restResponse = RestResponse.fail("无最佳路径结果");
                } else {
                    //物理删除重复的最佳路径分析结果
                    deleteNetworkanalystPath(networkId, ssId, ctfw, startLon, startLat, endLon, endLat);
                    //保存
                    NetworkanalystPath networkanalystPath = new NetworkanalystPath();
                    networkanalystPath.setId(UUIDGenerator.getUUID());
                    networkanalystPath.setSsId(ssId);//重点目标ID
                    networkanalystPath.setCtfw(ctfw);//出图范围km
                    networkanalystPath.setSsJzwmc(ssJzwmc);//重点目标名称
                    networkanalystPath.setBncsmc(bncsmc);//避难场所名称
                    networkanalystPath.setStartLon(startLon);
                    networkanalystPath.setStartLat(startLat);
                    networkanalystPath.setEndLon(endLon);
                    networkanalystPath.setEndLat(endLat);
                    networkanalystPath.setRouteLength(routeLength);//路径长度m
                    networkanalystPath.setGeom(line);//最佳路径空间数据
                    networkanalystPath.setDelFlag(YNEnum.N.toString());
                    networkanalystPath.setCreateUser(PlatformSessionUtils.getUserId());
                    networkanalystPath.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                    networkanalystPath.setVersionId(networkId);
                    //保存最佳路径分析结果
                    int index = saveNetworkanalystPath(networkanalystPath);
                    restResponse = RestResponse.succeed("最佳路径结果保存成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //根据起终点经纬度获取交通网络分析服务的最佳路径分析
    @Override
    public RestResponse getNetworkanalystPath(Map<String, Object> map) {
        map.put("type", "newNetworkanalystPath");
//        map.put("networkId","4718827a899b4f33a243462892359fc5");//工作空间发布交通网络分析服务ID
//        map.put("ssId","");//重点目标ID
//        map.put("ctfw","10");//出图范围km
//        map.put("ssJzwmc","测试重点目标名称");
//        map.put("bncsmc","测试避难场所名称");
//        map.put("startLon", "99.8");//起点经度
//        map.put("startLat", "30");//起点纬度
//        map.put("endLon", "102.4");//终点经度
//        map.put("endLat", "27.3");//终点纬度
        return getServerToken(map);//获取交通网络分析服务的最佳路径分析
    }

    //根据重点目标、出图范围和应急避难场所列表获取交通网络分析服务的最佳路径分析
    @Override
    public void getNetworkanalystPathList(String networkId, Site site, double ctfw, List<JcEmergcyShelterVo> jcEmergcyShelterVos) {
        //获取交通网络分析服务路径
        String networkUrl = getNetworkUrlById(networkId);
        if (PlatformObjectUtils.isNotEmpty(networkUrl)) {
            String ssId = site.getSsId();//重点目标ID
            String ssJzwmc = site.getSsJzwmc();//重点目标名称
            double startLon = site.getSsLongitude();
            double startLat = site.getSsLatitude();
            for (JcEmergcyShelterVo jcEmergcyShelterVo : jcEmergcyShelterVos) {
                String bncsmc = jcEmergcyShelterVo.getBncsmc();//避难场所名称
                double endLon = jcEmergcyShelterVo.getJesLongitude();
                double endLat = jcEmergcyShelterVo.getJesLatitude();
                Map<String, Object> map = new HashMap<>();
                map.put("type", "newNetworkanalystPath");
                map.put("networkId", networkId);//工作空间发布交通网络分析服务ID
                map.put("networkUrl", networkUrl);//工作空间发布交通网络分析服务路径
                map.put("ssId", ssId);//重点目标ID
                map.put("ctfw", ctfw);//出图范围km
                map.put("ssJzwmc", ssJzwmc);
                map.put("bncsmc", bncsmc);
                map.put("startLon", startLon);//起点经度
                map.put("startLat", startLat);//起点纬度
                map.put("endLon", endLon);//终点经度
                map.put("endLat", endLat);//终点纬度
                //获取交通网络分析服务的最佳路径分析
                getNetworkanalystPath(map);
            }
            //刷新指定超图工作空间数据源数据集
            boolean bool = getWorkspaceReload("sys_networkanalyst_path");
        }
    }

    //保存最佳路径分析结果
    public int saveNetworkanalystPath(NetworkanalystPath networkanalystPath) {
        String sql = "insert into sys_networkanalyst_path " +
                "(id,ss_id,start_lon,start_lat,end_lon,end_lat,del_flag,create_user,create_time,geom,route_length,ctfw,ss_jzwmc,bncsmc,version_id) " +
                "values (:id,:ssId,:startLon,:startLat,:endLon,:endLat,:delFlag,:createUser,:createTime," +
                "st_geomfromtext(:geom,4490),:routeLength,:ctfw,:ssJzwmc,:bncsmc,:versionId)";
        BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(networkanalystPath);
        return namedParameterJdbcTemplate.update(sql, source);
    }

    //物理删除重点目标ID、出图范围、起终点经纬度相同的最佳路径分析结果
    public void deleteNetworkanalystPath(String networkId, String ssId, Double ctfw, Double startLon, Double startLat, Double endLon, Double endLat) {
        String sql = "delete from sys_networkanalyst_path" +
                " where ss_id='" + ssId + "' and ctfw = " + ctfw +
                " and version_id='" + networkId + "' and start_lon = " + startLon + " and start_lat = " + startLat +
                " and end_lon = " + endLon + " and end_lat = " + endLat;
        jdbcTemplate.update(sql);
    }

    //工作空间发布交通网络分析服务
    @Override
    public RestResponse newWorkspaceNetworkVersion(NetworkanalystVersion networkanalystVersion) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "newWorkspaceNetwork");
        map.put("networkanalystVersion", networkanalystVersion);
//        map.put("smwuUrl","E:/MapData/testfilenetwork/testfilenetwork/testfilenetwork.smwu");//工作空间路径
//        map.put("udbxUrl","E:/MapData/testfilenetwork/testfilenetwork/filenetwork.udbx");//工作空间数据源文件路径
//        map.put("datasource","filenetwork");//数据源名称
//        map.put("dataset","filenetwork_Network");//工作空间内的网络数据集名称
        return getServerToken(map);//工作空间发布交通网络分析服务
    }

    //工作空间发布地图服务
    @Override
    public RestResponse newWorkspaceRestMap(NetworkanalystVersion networkanalystVersion) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "workspaceRestMap");
        map.put("networkanalystVersion", networkanalystVersion);
//        map.put("smwuUrl","E:/MapData/testBeijing/testBeijing.smwu");//工作空间路径
//        map.put("udbxUrl","E:/MapData/testBeijing/testBeijing.udbx");//工作空间数据源文件路径
//        map.put("datasource","testBeijing");//数据源名称
//        map.put("dataset","testBeijing_Network");//工作空间内的网络数据集名称
        return getServerToken(map);//工作空间发布交通网络分析服务
    }

    //删除超图工作空间服务并逻辑删除版本
    @Override
    public boolean deleteWorkspace(NetworkanalystVersion networkanalystVersion) {
        boolean bool = false;
        if (networkanalystVersion != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("type", "deleteWorkspace");
            map.put("networkanalystVersion", networkanalystVersion);
            RestResponse res = getServerToken(map);//获取超图工作空间全部地图服务url列表
            if (res.getCode() == 200) {
                bool = true;
            }
        }
        return bool;
    }

    //根据用户获取基础地理数据超图工作空间全部地图服务url列表
    @Override
    public List<String> getRestMapUrlList(String dataVersion) {
        List<String> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("type", "getRestMapUrlList");
        //根据用户获取最新的地图服务
        String url = getLatestWorkspaceVersion(dataVersion);
        map.put("mapUrl", url);
        RestResponse res = getServerToken(map);//获取超图工作空间全部地图服务url列表
        if (res.getCode() == 200) {
            list = (List<String>) res.getData();
        }
        return list;
    }

    //根据ID逻辑删除版本
    public boolean deleteNetworkanalystVersionById(String id) {
        try {
            String sql = "update sys_networkanalyst_version set del_flag ='" + YNEnum.Y.toString() + "' where id='" + id + "'";
            jdbcTemplate.update(sql);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //根据版本号删除超图工作空间服务
    @Override
    public boolean deleteWorkspaceByVersion(String dataVersion) {
        //根据ID查询交通网络分析服务版本信息
        NetworkanalystVersion networkanalystVersion = getNetworkVersionByVersion(dataVersion);
        //删除超图工作空间服务并逻辑删除版本
        return deleteWorkspace(networkanalystVersion);
    }

    //获取新的交通网络分析服务版本号
    @Override
    public String getNetworkanalystVersionCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String date = df.format(new Date());
        String version = date + "LJGH";
        int count = 0;
        try {
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            String date1 = df1.format(new Date());
            String sql = "select count(*) from sys_networkanalyst_version where version like '%LJGH%' and cast(create_time as varchar) like '%" + date1 + "%'";
            count = jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            count = 0;
        }
        count++;
        if (count < 10) {
            version += "000" + count;
        } else if (count < 100) {
            version += "00" + count;
        } else if (count < 1000) {
            version += "0" + count;
        } else {
            version += count;
        }
        return version;
    }

    //获取新的地图服务版本号
    @Override
    public String getNewWorkspaceVersionCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String date = df.format(new Date());
        String version = date + "MAP";
        int count = 0;
        try {
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            String date1 = df1.format(new Date());
            String sql = "select count(*) from sys_networkanalyst_version where version like '%MAP%' and cast(create_time as varchar) like '%" + date1 + "%'";
            count = jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            count = 0;
        }
        count++;
        if (count < 10) {
            version += "000" + count;
        } else if (count < 100) {
            version += "00" + count;
        } else if (count < 1000) {
            version += "0" + count;
        } else {
            version += count;
        }
        return version;
    }

    //根据用户获取最新的地图服务
    @Override
    public String getLatestWorkspaceVersion(String dataVersion) {
        String url = null;
        try {
            String createUser = PlatformSessionUtils.getUserId();
            String sql = "select network_url from sys_networkanalyst_version where version like '%MAP%' and version='" + dataVersion + "' and create_user='" + createUser + "' order by create_time desc limit 1";
            url = jdbcTemplate.queryForObject(sql, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    //保存交通网络分析服务版本信息
    public int saveNetworkanalystVersion(NetworkanalystVersion networkanalystVersion) {
        String sql = "insert into sys_networkanalyst_version " +
                "(id,smwu_url,udbx_url,datasource,dataset,network_url,province,city,county,version,type," +
                "del_flag,create_user,create_user_name,create_time,create_province_id,province_id,city_id,county_id,remark,attach_ids) " +
                "values (:id,:smwuUrl,:udbxUrl,:datasource,:dataset,:networkUrl,:province,:city,:county,:version,:type," +
                ":delFlag,:createUser,:createUserName,:createTime,:createProvinceId,:provinceId,:cityId,:countyId,:remark,:attachIds)";
        BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(networkanalystVersion);
        return namedParameterJdbcTemplate.update(sql, source);
    }

    //批量逻辑删除交通网络分析服务版本信息
    @Override
    public RestResponse deleteNetworkanalystVersion(String idsStr) {
        try {
            List<String> ids = new ArrayList<>();
            if (PlatformObjectUtils.isEmpty(ids)) {
                String[] idArr = idsStr.split(",");
                for (int i = 0; i < idArr.length; i++) {
                    String id = idArr[i];
                    //根据ID查询交通网络分析服务版本信息
                    NetworkanalystVersion networkanalystVersion = getNetworkVersionById(id);
                    //删除超图工作空间服务并逻辑删除版本
                    deleteWorkspace(networkanalystVersion);
                }
            }
            /*List<String> ids = new ArrayList<>();
            if (PlatformObjectUtils.isEmpty(ids)) {
                String[] idArr = idsStr.split(",");
                for(int i=0;i<idArr.length;i++){
                    String id = idArr[i];
                    ids.add(id);
                }
            }
            String sql = "update sys_networkanalyst_version set del_flag ='" + YNEnum.Y.toString() + "' where id in (:ids)";
            Map idMap = new HashMap();
            idMap.put("ids", ids);
            namedParameterJdbcTemplate.update(sql, idMap);*/
            return RestResponse.succeed("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //获取交通网络分析服务路径
    public String getNetworkUrlById(String networkId) {
        String sql = "select network_url from sys_networkanalyst_version where id='" + networkId + "' and del_flag ='" + YNEnum.N.toString() + "'";
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    //获取用户的所属省份ID
    public String getUserProvinceId() {
        String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        String provinceId = sUser.getProvinceId();
        if (PlatformObjectUtils.isEmpty(provinceId)) {
            provinceId = null;
        }
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        //如果所有角色包括国家级管理员
        if (allRole.contains(FxfzConstants.AQBZ_GJJGLY_ROLE)) {
            provinceId = "";
        }

        return provinceId;
    }

    //按国家级、省级查询交通网络分析服务版本列表
    @Override
    public RestResponse getNetworkVersionList(NetworkanalystVersion networkanalystVersion) {
        try {
            String type = networkanalystVersion.getType();
            String version = networkanalystVersion.getVersion();
            String provinceId = networkanalystVersion.getProvinceId();
            String cityId = networkanalystVersion.getCityId();
            String countyId = networkanalystVersion.getCountyId();
            String sql = "select * from sys_networkanalyst_version " +
                    "where version like '%LJGH%' and  type='" + type + "' and del_flag ='" + YNEnum.N.toString() + "'";
            //获取用户的所属省份ID
            String createProvinceId = getUserProvinceId();
            if (type.equals("0")) {//国家级
                //可查全部国家级
            } else {//省级
                //国家级管理员可查全部省级
                if (PlatformObjectUtils.isNotEmpty(createProvinceId)) {
                    sql += " and create_province_id='" + createProvinceId + "'";//按省查
                }
            }
            if (PlatformObjectUtils.isNotEmpty(version)) {
                sql += " and version like '%" + version + "%'";
            }
            if (PlatformObjectUtils.isNotEmpty(provinceId) && !provinceId.equals("全国")) {
                sql += " and province_id='" + provinceId + "'";
            }
            if (PlatformObjectUtils.isNotEmpty(cityId) && !cityId.equals("全部")) {
                sql += " and city_id='" + cityId + "'";
            }
            if (PlatformObjectUtils.isNotEmpty(countyId) && !countyId.equals("全部")) {
                sql += " and county_id='" + countyId + "'";
            }
            sql += " order by create_time desc";
            Integer total = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class)).size();
            int curPage = networkanalystVersion.getCurPage();
            int pageSize = networkanalystVersion.getPageSize();
            int firstIndex = (curPage - 1) * pageSize;
            int lastIndex = pageSize;
            StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
            sql += limitSql;
            List<NetworkanalystVersion> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
            Map<String, Object> map = new HashMap();
            map.put("total", total);
            map.put("rows", list);
            return RestResponse.succeed(map);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //分页查询交通网络分析服务版本列表
    @Override
    public RestResponse getNetworkVersionListPage(int curPage, int pageSize) {
        try {
            String sql = "select * from sys_networkanalyst_version " +
                    "where version like '%LJGH%' and del_flag ='" + YNEnum.N.toString() + "'";
            //获取用户的所属省份ID
            String createProvinceId = getUserProvinceId();
            if (createProvinceId.equals("")) {//国家级管理员为""
                //可查全部
            } else {
                if (PlatformObjectUtils.isNotEmpty(createProvinceId)) {//创建人省份ID
                    sql += " and (create_province_id='" + createProvinceId + "' or type='0')";//按省查省级、全部国家级
                }
            }
            sql += " order by create_time desc";
            Integer total = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class)).size();
            int firstIndex = (curPage - 1) * pageSize;
            int lastIndex = pageSize;
            StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
            sql += limitSql;
            List<NetworkanalystVersion> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
            Map<String, Object> map = new HashMap();
            map.put("total", total);
            map.put("rows", list);
            return RestResponse.succeed(map);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //根据ID查询交通网络分析服务版本信息
    @Override
    public NetworkanalystVersion getNetworkVersionById(String id) {
        NetworkanalystVersion networkanalystVersion = null;
        try {
            String sql = "select * from sys_networkanalyst_version where id='" + id + "'";
            networkanalystVersion = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return networkanalystVersion;
    }

    //根据版本查询交通网络分析服务版本信息
    @Override
    public NetworkanalystVersion getNetworkVersionByVersion(String version) {
        NetworkanalystVersion networkanalystVersion = null;
        try {
            String sql = "select * from sys_networkanalyst_version where version='" + version + "'";
            networkanalystVersion = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(NetworkanalystVersion.class));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return networkanalystVersion;
    }

    //获取Web打印出图模板列表
    @Override
    public List<TemplateEntity> getWebprintingLayoutsList() {
        List<TemplateEntity> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("type", "getWebprintingLayoutsList");
        RestResponse res = getServerToken(map);//获取Web打印出图模板列表
        if (res.getCode() == 200) {
            list = (List<TemplateEntity>) res.getData();
        }
        return list;
    }

    //获取Web打印出图模板列表
    private RestResponse supermapGetTemplateEntityList(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/webprinting/rest/webprinting/v1/layouts.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONArray body = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return null;
            }
            if (body.size() > 0) {
                List<TemplateEntity> templateEntityList = new ArrayList<>();
                for (int i = 0; i < body.size(); i++) {
                    String templateName = body.getJSONObject(i).getString("templateName");
                    Integer webMapFrameSizeX = body.getJSONObject(i).getJSONArray("webMapFrameSize").getInteger(0);
                    Integer webMapFrameSizeY = body.getJSONObject(i).getJSONArray("webMapFrameSize").getInteger(1);
                    TemplateEntity templateEntity = new TemplateEntity();
                    templateEntity.setTemplateName(templateName);
                    templateEntity.setWebMapFrameSizeX(webMapFrameSizeX);
                    templateEntity.setWebMapFrameSizeY(webMapFrameSizeY);
                    templateEntityList.add(templateEntity);
                }
                restResponse = RestResponse.succeed(templateEntityList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    //上传模板文件到超图模板目录
    @Override
    public RestResponse uploadTemplateFile(String attachId) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "uploadTemplateFile");
        String srcFile = null;
        //根据id和文件名获取真实的放在磁盘上的文件
        AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(attachId);
        String attachPath = attachmentInfoEntity.getAttachPath();
        if (attachPath.endsWith(".ult")) {
            srcFile = attachmentInfoEntity.getFileDirId() + attachPath;
        }
        map.put("srcFile", srcFile);
        RestResponse res = getServerToken(map);//获取Web打印出图模板列表
        return res;
    }

    //上传模板文件到超图模板目录
    private RestResponse supermapPostTemplateFile(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            //欲上传的源文件路径
            String srcFile = (String) map.get("srcFile");
//            srcFile = "C:/Users/lenovo/Desktop/新建文件夹/fxfzaqbz-hf_1699350083222.ult";
            if (PlatformObjectUtils.isEmpty(srcFile)) {
                System.out.println("无上传的源文件路径");
                return RestResponse.fail("无上传的源文件路径！");
            }
            File zipFile = null;
            if (srcFile.endsWith(".ult")) {
                String originFile = srcFile;
                String timeStamp = System.currentTimeMillis() + "";//时间戳，防止重名
                srcFile = srcFile.substring(0, srcFile.lastIndexOf("/")) + "/fxfzaqbz-hf_" + timeStamp + ".ult";
                //复制文件，设置文件名，防止原文件名称超长
                FileUtil.copy(originFile, srcFile, true);
                //将.ult模板文件打包压缩包.zip
                //获取复制的文件
                File ultFile = new File(srcFile);
                //压缩文件路径
                srcFile = srcFile.substring(0, srcFile.lastIndexOf(".")) + ".zip";
                // 打成压缩包
                zipFile = new File(srcFile);
                FileOutputStream zipFos = new FileOutputStream(zipFile);
                ArchiveOutputStream archOut = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, zipFos);
                if (archOut instanceof ZipArchiveOutputStream) {
                    ZipArchiveOutputStream zos = (ZipArchiveOutputStream) archOut;
                    ZipArchiveEntry zipEntry = new ZipArchiveEntry(ultFile, ultFile.getName());
                    zos.putArchiveEntry(zipEntry);
                    zos.write(FileUtils.readFileToByteArray(ultFile));
                    zos.closeArchiveEntry();
                    zos.flush();
                    zos.close();
                }
                // 删除复制的文件
                if (ultFile.exists()) {
                    ultFile.delete();
                }
            } else {
                System.out.println("源文件不是超图Web打印模板");
                return RestResponse.fail("源文件不是超图Web打印模板！");
            }
//            String srcFile = "C:/Users/lenovo/Desktop/新建文件夹/fxfzaqbz-hf_1699350083999.zip";
            String fileName = srcFile.substring(srcFile.lastIndexOf("/") + 1);
            //欲上传的目标位置（位于服务器，相对于iServer应用目录/webapps/iserver/）
//            String destFile = "C:/Users/lenovo/Desktop/192/supermap-iserver-1111-22428-6922-windows-x64-deploy-usv3236/supermap-iserver-1111-22428-6922-windows-x64-deploy/webapps/iserver/templates/webprinting-layouts/fxfzaqbz-hf_1699350083888.zip";
//            String destFile = "/templates/webprinting-layouts/"+fileName;//相对路径
//            String destFile = "/usr/supermaprootnew/iserver/webapps/iserver/templates/webprinting-layouts/"+fileName;//绝对路径
//            String destFile = "/usr/supermaproot-111a/supermap-iserver-11.1.1a-linux-x64/supermap-iserver-11.1.1a-linux-x64/webapps/iserver/templates/webprinting-layouts/"+fileName;//绝对路径
//            String destFile = "/usr/supermaproot-333a/supermap-iserver-1111-23101-7024-linux-x64-deploy/webapps/iserver/templates/webprinting-layouts/";//绝对路径
            //查询字典--超图数据源工作空间文件路径
            DictItemEntity dte = dictItemRepository.findOneByDictItemCodeAndDictId("webprinting", "100001");
            String destFile = dte.getDictItemName();//工作空间文件路径
            destFile += fileName;
            System.out.println(destFile);
            //是否覆盖
            boolean overwrite = true;
            //是否解压，上传的是zip文件，且unzip为true时，上传后iServer会将zip文件解压
            boolean unzip = true;

            String dataUrl = iServerHttp + "/iserver/manager/filemanager/uploadtasks.rjson?token=" + serverToken;
            dataUrl += "&toFile=" + destFile + "&overwrite=" + overwrite + "&unzip=" + unzip;

            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

            //获取文件
            File file = new File(srcFile);
            if (!file.isFile()) {
                System.out.println("欲上传的源文件不存在。");
                return RestResponse.fail("欲上传的源文件不存在！");
            }
            //通过uploadtasks资源，创建一个uploadtask资源用于文件上传，并返回uploadtask资源的URL
            //创建时传入源文件的大小、目标路径、MD5，服务器端可据此判断磁盘空间是否充足，并在上传完成后进行MD5校验。
            long srcFileSize = file.length();
            String md5 = getMD5(file);
            String uploadtaskurl = getUploadTaskURL(dataUrl, srcFileSize, destFile, md5, serverToken);
            System.out.println("上传模板文件任务--" + uploadtaskurl);
            if (PlatformObjectUtils.isNotEmpty(uploadtaskurl)) {
                uploadtaskurl += ".json";
                uploadtaskurl = uploadtaskurl + "?toFile=" + destFile + "&overwrite=" + overwrite + "&unzip=" + unzip + "&token=" + serverToken;
                MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
                bodyMap.add("file", new FileSystemResource(file));
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<String> response = restTemplate.exchange(uploadtaskurl, HttpMethod.POST, requestEntity, String.class);
                JSONObject body = JSON.parseObject(JSON.parseObject(JSON.toJSONString(response)).getString("body"));
                System.out.println(body);
                String resultFileName = body.getString("fileName");//	上传文件或目录的名称。
//                String resultFilePath = body.getString("filePath");//文件上传后的目标文件或目录，用相对路径表示。相对路径的起算目录为 iServer 应用目录，如 Package 包中为%SuperMap iServer_HOME%\webapp\ iserver 目录 。
//                String fileSize = body.getString("fileSize");//	上传文件的大小，单位为字节。
//                String isDirectory = body.getString("isDirectory");//是否是目录，默认为 false。
                System.out.println("上传模板文件到超图模板目录成功" + resultFileName);
                // 删除压缩包
                if (zipFile.exists()) {
                    zipFile.delete();
                }
                /*//判断模板是否已在超图Web打印模板列表中
                boolean bool = false;
                while(bool==false){
                    Thread.sleep(10000);//10秒
                    //获取Web打印出图模板列表
                    List<TemplateEntity> templateEntityList = getWebprintingLayoutsList();
                    if(templateEntityList.size()>0){
                        for(TemplateEntity entity : templateEntityList){
                            if(resultFileName.equals(entity.getTemplateName())){
                                bool = true;
                                break;
                            }
                        }
                    }
                }
                System.out.println("成功发布模板文件到超图模板目录"+resultFileName);*/
                return RestResponse.succeed(resultFileName);
            } else {
                return RestResponse.fail("上传失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
    }

    //计算 file的MD5码
    private static String getMD5(File file) {
        String result = "";
        try {
            byte[] filebytes = FileUtils.readFileToByteArray(file);
            final char[] hexDigits = "0123456789abcdef".toCharArray();
            final byte[] md5 = MessageDigest.getInstance("MD5").digest(filebytes);
            final char[] md5Chars = new char[32];
            int i = 0;
            for (final byte b : md5) {
                md5Chars[i++] = hexDigits[(b >> 4) & 0xF];
                md5Chars[i++] = hexDigits[b & 0xF];
            }
            result = new String(md5Chars);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException("No MD5 algorithm, unable to compute MD5");
        }
        return result;
    }

    //通过uploadtasks资源，创建一个uploadtask资源用于文件上传，并返回uploadtask资源的URL
    //创建时传入源文件的大小、目标路径、MD5，服务器端可据此判断磁盘空间是否充足，并在上传完成后进行MD5校验。
    public String getUploadTaskURL(String uploadtasksurl, long srcfileSize, String destFile, String md5, String token) throws ClientProtocolException, IOException {
        String result = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(uploadtasksurl + "?token=" + token);
        //创建时传入源文件的大小、目标路径、MD5，服务器端可据此判断磁盘空间是否充足，并在上传完成后进行MD5校验。
        JSONObject entityStr = new JSONObject();
        try {
            entityStr.put("fileSize", srcfileSize);
            entityStr.put("filePath", destFile);
//            entityStr.put("path", destFile);
            entityStr.put("md5", md5);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        StringEntity entity = new StringEntity(entityStr.toString(), "utf-8");
        entity.setContentType(new BasicHeader(org.apache.http.protocol.HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(entity);

        org.apache.http.HttpResponse response = client.execute(post);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        InputStream is = responseEntity.getContent();
        String responseEntityStr = new String(IOUtils.toByteArray(is), "utf-8");
        try {
            JSONObject body = JSON.parseObject(responseEntityStr);
            result = body.getString("newResourceLocation");
            System.out.println(result);
        } catch (JSONException e) {
            e.printStackTrace();
            result = null;
        }
        return result;
    }

    //向数据管理子系统查询数据
    @Override
    public RestResponse getJCSJ(String url, int tab, JSONObject valueMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzaqbz");
        headers.set("subsystemCode", "anbao");
        HttpEntity<JSONObject> r = new HttpEntity<>(valueMap, headers);
        RestResponse resp = null;
        try {
            if (tab == 1) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 2) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 3) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 4) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 5) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data").getJSONArray("data");
                resp = RestResponse.succeed(data);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }
}
